<?php


namespace app\app\controller\user;


use app\model\DeptModel;
use app\model\UserModel;
use support\Request;

class Dept
{
    protected $user_id = 0;

    public function beforeAction(Request $request){
        $this->user_id = $request->user_id;
    }

    public function tree(){
        $userModel = new UserModel();
        $user = $userModel->info($this->user_id);
        $tree = [];
        $child = [];
        $this->getChild($user['company_id'],$child);
        $this->createTree($child,$tree);
        return success($tree);
    }

    public function getChild($parent_id,&$rest=Array()){
        $deptModel = new DeptModel();
        $dept = $deptModel->field("dept_id,dept_name,parent_id,dept_full_name")->where([['deleted','=',0]])->find($parent_id)->toArray();
        $dept['unfold'] = 0;
        if($rest==[]){
            $rest=[$dept];
        }else{
            $rest[]=$dept;
        }
        $child = $deptModel->where([['parent_id','=',$parent_id]])->field("dept_id,dept_name,parent_id,dept_full_name")->where([['deleted','=',0]])->select()->toArray();
        foreach ($child as $k=>$v){
            $this->getChild($v['dept_id'],$rest);
        }
    }

    private function createTree($rest,&$res=Array()){
        $userModel = new UserModel();
        $tree = [];
        $newData = [];
        foreach ($rest as $datum) {
            $newData[$datum['dept_id']] = $datum;
            $newData[$datum['dept_id']]['user'] = $userModel::with(['position'])->where([['dept_id','=',$datum['dept_id']],['user_id','>',10000],['deleted','=',0]])->select()->visible(['user_id','username','realname','position_name','mobile','avatar'])->toArray();
        }
        foreach ($newData as $key => $datum) {
            if ($datum['parent_id'] > 0) {
                $newData[$datum['parent_id']]['child'][] = &$newData[$key];

            } else {
                $tree[] = &$newData[$datum['dept_id']];
            }
        }
        $res = $tree;
    }

}